﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.Remoting.Messaging;
using MoonLight.LibCommon;
using MoonLight.LibSocket;
using Autumn.Common;

namespace Autumn.NetSession
{
    class Acceptor : Notifier
    {
        public Acceptor(string ip, int port, Notifier parent)
        {
            m_sock = new AsynTcpSocket(this);
            m_listen_ip = ip;
            m_listen_port = port;
            m_parent = parent;
        }

        public void StartListen()
        {
            Logger.WriteLog("start listen...");
            if (m_sock.CreateSocket() < 0) {
                Logger.WriteLog("create socket fail");
                //TODO: info upper layer
                return;
            }
            if (m_sock.Listen(m_listen_ip, m_listen_port, 8) < 0) {
                Logger.WriteLog("listen socket fail");
                //TODO: info upper layer
                return;
            }
        }

        public void EndListen(IAsyncResult result)
        {
            Logger.WriteLog("stop listen...");
            AsyncResult res = (AsyncResult)result;
            ProjectDefine.AcceptorDelegate apt_delegate = (ProjectDefine.AcceptorDelegate)res.AsyncDelegate;
            apt_delegate.EndInvoke(res);
        }

        public override void handle_message(MessageInfo msg)
        {
            switch ((CommonDefine.MsgType_e)msg.msg_type)
            {
                case CommonDefine.MsgType_e.MSG_TCP_ACCEPT:
                    {
                        Logger.WriteLog("accept a connection");
                        MessageInfo msg_info = new MessageInfo(ProjectDefine.ProjectMsgType_e.MSG_ADD_SESSION);
                        msg_info.msg_data = msg.msg_data;
                        m_parent.handle_message(msg_info);
                    }
                    break;
                case CommonDefine.MsgType_e.MSG_TCP_ERR:
                    { 
                    }
                    break;
                default:
                    {
                        Logger.WriteLog("unknow msg type [" + (int)msg.msg_type + "]");
                    }
                    break;
            }
        }

        private string m_listen_ip;
        private int m_listen_port;
        private AsynTcpSocket m_sock;
        private Notifier m_parent;
    }
}
